<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Download, Check, Close } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'

// 定义类型
interface RepairPart {
  id: number
  repairProcessId: number
  partName: string
  quantity: number
  unitPrice: number
  totalPrice: number
  status: string
  approvalNotes: string | null
  approvalTime: string | null
  partFileUrl: string | null
}

interface RepairPartListResponse {
  current: number
  total: number
  pages: number
  size: number
  records: RepairPart[]
}

interface RepairPartApprovalModel {
  id: number
  status: string
  approvalNotes: string | null
}

// 定义常量
const statusTypeMap = {
  '待审批': '待审批',
  '已通过': '已通过',
  '已驳回': '已驳回'
} as const

const getStatusTypeLabel = (value: string): string => {
  return statusTypeMap[value as keyof typeof statusTypeMap] || '未知状态'
}

const repairPartApi = {
  getRepairPartList: (params: any) => {
    return request<RepairPartListResponse>({
      method: 'GET',
      url: '/repair/part/list',
      params: params
    })
  },

  approveRepairPart: (data: RepairPartApprovalModel) => {
    return request<string>({
      method: 'POST',
      url: '/repair/part/approve',
      data: data
    })
  }
}

// 表单配置
const ListFields = [
  {
    label: 'ID',
    prop: 'id',
    type: 'input',
    width: '80px'
  },
  {
    label: '维修过程ID',
    prop: 'repairProcessId',
    type: 'input',
    width: '120px'
  },
  {
    label: '配件名称',
    prop: 'partName',
    type: 'input',
    width: '150px'
  },
  {
    label: '数量',
    prop: 'quantity',
    type: 'input',
    width: '80px'
  },
  {
    label: '单价',
    prop: 'unitPrice',
    type: 'input',
    width: '100px'
  },
  {
    label: '总价',
    prop: 'totalPrice',
    type: 'input',
    width: '100px'
  },
  {
    label: '状态',
    prop: 'status',
    type: 'input',
    slot: true,
    width: '100px',
    formatter: (row: RepairPart) => getStatusTypeLabel(row.status)
  },
  {
    label: '附件',
    prop: 'partFileUrl',
    slot: true,
    width: '120px'
  },
  {
    label: '审批备注',
    prop: 'approvalNotes',
    type: 'input',
    width: '150px'
  },
  {
    label: '审批时间',
    prop: 'approvalTime',
    type: 'datetime',
    width: '166px'
  },
  {
    label: '操作',
    prop: 'action',
    slot: true,
    width: '160px'
  }
]

// 组件状态
let repairPartList = ref<RepairPart[]>()
const searchParams = ref({
  repairProcessId: null as number | null,
  status: null as string | null
})

const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)

const approvalDialogVisible = ref(false)
const currentApprovalPart = ref<RepairPartApprovalModel>({
  id: 0,
  status: '已通过',
  approvalNotes: null
})

const isApproving = ref(false)

// 生命周期
onMounted(async () => {
  init()
})

// 方法
const init = async () => {
  getDataListWithCondition()
}

const getDataListWithCondition = async () => {
  let params = {
    page: pageNum.value,
    size: pageSize.value,
    repairProcessId: searchParams.value.repairProcessId,
    status: searchParams.value.status
  }

  const filteredParams = Object.entries(params).reduce((acc, [key, value]) => {
    if (value !== null && value !== undefined && value !== '') {
      (acc as any)[key] = value;
    }
    return acc;
  }, {});
  console.log(filteredParams);

  try {
    const response = await repairPartApi.getRepairPartList(params)
    repairPartList.value = response.data.records
    total.value = response.data.total
  } catch (error) {
    ElMessage.error('获取数据失败')
  }
}

// 文件下载方法
const downloadFile = (url: string) => {
  if (!url) {
    ElMessage.warning('没有可下载的附件')
    return
  }
  
  const link = document.createElement('a')
  link.href = url
  link.target = '_blank'
  link.download = url.split('/').pop() || 'attachment'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

const showApprovalDialog = (part: RepairPart, status: string) => {
  currentApprovalPart.value = {
    id: part.id,
    status: status,
    approvalNotes: part.approvalNotes || null
  }
  approvalDialogVisible.value = true
}

const handleApproval = async () => {
  if (isApproving.value) return
  
  try {
    isApproving.value = true
    
    // 对于驳回操作，要求必须填写审批备注
    if (currentApprovalPart.value.status === '已驳回' && !currentApprovalPart.value.approvalNotes?.trim()) {
      ElMessage.warning('驳回操作必须填写审批备注')
      return
    }
    
    await repairPartApi.approveRepairPart(currentApprovalPart.value)
    
    ElMessage.success('审批成功')
    approvalDialogVisible.value = false
    getDataListWithCondition()
  } catch (error) {
    console.error('审批出错:', error)
    ElMessage.error('审批失败')
  } finally {
    isApproving.value = false
  }
}

const search = () => {
  pageNum.value = 1
  getDataListWithCondition()
}

const resetSearch = () => {
  searchParams.value = {
    repairProcessId: null,
    status: null
  }
  pageNum.value = 1
  getDataListWithCondition()
}

const onSizeChange = (size: number) => {
  pageSize.value = size
  getDataListWithCondition()
}

const onCurrentChange = (num: number) => {
  pageNum.value = num
  getDataListWithCondition()
}

const isImageFile = (url: string): boolean => {
  return /\.(jpg|jpeg|png|gif|bmp|webp)$/i.test(url)
}
</script>
<template>
  <el-card class="card-box">
    <div class="header">
      <h2>维修配件审批管理</h2>
    </div>

    <el-form inline class="filter-bar">
      <el-form-item label="维修过程ID:">
        <el-input
          v-model.number="searchParams.repairProcessId"
          placeholder="请输入维修过程ID"
          type="number"
          clearable
          class="input-short"
        />
      </el-form-item>
      
      <el-form-item label="状态:">
        <el-select
          v-model="searchParams.status"
          placeholder="请选择状态"
          clearable
          class="input-short"
        >
          <el-option
            v-for="item in Object.values(statusTypeMap)"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="search()">
          <el-icon><Search /></el-icon>搜索
        </el-button>
        <el-button @click="resetSearch()">
          <el-icon><Refresh /></el-icon>重置
        </el-button>
      </el-form-item>
    </el-form>

    <div class="responsive-table-container">
      <table class="custom-table">
        <thead>
          <tr>
            <th v-for="col in ListFields" :key="col.prop" :width="col.width">
              {{ col.label }}
            </th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="item in repairPartList" :key="item.id">
            <td>{{ item.id }}</td>
            <td>{{ item.repairProcessId }}</td>
            <td>{{ item.partName }}</td>
            <td>{{ item.quantity }}</td>
            <td>¥{{ item.unitPrice?.toFixed(2) || '0.00' }}</td>
            <td>¥{{ item.totalPrice?.toFixed(2) || '0.00' }}</td>
            <td>
              <el-tag :type="item.status === '已通过' ? 'success' : item.status === '已驳回' ? 'danger' : 'warning'">
                {{ getStatusTypeLabel(item.status) }}
              </el-tag>
            </td>
            <td>
  <template v-if="item.partFileUrl">
    <template v-if="isImageFile(item.partFileUrl)">
      <el-popover
        placement="left"
        trigger="hover"
        :width="325"
        popper-class="image-popover"
      >
        <template #reference>
          <img
            :src="item.partFileUrl"
            class="thumbnail-img"
            alt="缩略图"
            @click="downloadFile(item.partFileUrl)"
          />
        </template>
        <img :src="item.partFileUrl" class="preview-img" alt="大图预览" />
      </el-popover>
      <a
        :href="item.partFileUrl"
        :download="item.partFileUrl.split('/').pop()"
        class="thumbnail-download"
        title="点击下载"
      />
    </template>
    <el-button
      v-else
      :icon="Download"
      type="primary"
      link
      @click="downloadFile(item.partFileUrl)"
    >
      下载附件
    </el-button>
  </template>
  <span v-else class="no-attachment">无附件</span>
</td>
            <td>{{ item.approvalNotes || '-' }}</td>
            <td>{{ item.approvalTime || '-' }}</td>
            <td>
              <div class="action-btns">
                <el-button
                  v-if="item.status === '待审批'"
                  :icon="Check"
                  circle
                  plain
                  size="small"
                  type="success"
                  @click="showApprovalDialog(item, '已通过')"
                />
                <el-button
                  v-if="item.status === '待审批'"
                  :icon="Close"
                  circle
                  plain
                  size="small"
                  type="danger"
                  @click="showApprovalDialog(item, '已驳回')"
                />
                <span v-if="item.status !== '待审批'" class="no-action">-</span>
              </div>
            </td>
          </tr>
          <tr v-if="repairPartList?.length === 0">
            <td colspan="11" class="text-center py-4">
              <el-empty description="暂无数据" />
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :page-sizes="[3, 5, 7, 10]"
        layout="total, sizes, prev, pager, next, jumper"
        background
        :total="total"
        @size-change="onSizeChange"
        @current-change="onCurrentChange"
      />
    </div>

    <!-- 审批对话框 -->
    <el-dialog 
      v-model="approvalDialogVisible" 
      :title="`配件审批 - ${currentApprovalPart.status === '已通过' ? '通过' : '驳回'}`" 
      width="500px"
      class="compact-dialog"
    >
      <el-form :model="currentApprovalPart" label-width="100px">
        <el-form-item label="审批备注">
          <el-input
            v-model="currentApprovalPart.approvalNotes"
            type="textarea"
            :rows="3"
            :placeholder="currentApprovalPart.status === '已驳回' ? '请输入驳回原因（必填）' : '请输入审批备注（可选）'"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="approvalDialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleApproval"
          :loading="isApproving"
        >
          确认
        </el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<style lang="scss" scoped>
.card-box {
  width: 100%;
  max-width: 100%;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  display: flex;
  flex-direction: column;
  padding: 0;
  overflow: hidden;
}

.header {
  padding: 0.8rem 1.2rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #e6eaf0;
  background-color: #f7f9fc;
  
  h2 {
    font-weight: 600;
    font-size: 1.4rem;
    color: #333;
    user-select: none;
    margin: 0;
  }
}

.filter-bar {
  padding: 0.8rem 1.2rem;
  background-color: #fafbfc;
  border-bottom: 1px solid #e6eaf0;
  display: flex;
  flex-wrap: nowrap;
  align-items: center;
  overflow-x: auto;
  white-space: nowrap;
  gap: 0.8rem;

  .el-form-item {
    margin-bottom: 0 !important;
    flex-shrink: 0;
    
    label {
      font-weight: 500;
      color: #606266;
      font-size: 0.9rem;
    }
    
    .input-short {
      width: 150px;
    }
  }

  .el-button {
    height: 32px;
    font-weight: 500;
    padding: 0 12px;
    flex-shrink: 0;
  }
}

.responsive-table-container {
  overflow-x: auto;
  background: #fff;
  padding: 0.8rem;
}

.custom-table {
  width: 100%;
  border-collapse: separate;
  border-spacing: 0 6px;
  font-size: 0.9rem;

  thead tr {
    background-color: #f5f7fa;
    color: #606266;
    font-weight: 600;
    user-select: none;
  }

  th, td {
    padding: 8px 12px;
    text-align: left;
    vertical-align: middle;
    white-space: nowrap;
  }

  th {
    font-size: 0.85rem;
  }

  tbody tr {
    background-color: #fff;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
    transition: background-color 0.2s ease;

    &:hover {
      background-color: #f4f9ff;
    }
  }

  .no-attachment {
    color: #a9abb0;
    font-style: italic;
    user-select: none;
    font-size: 0.85rem;
  }

  .no-action {
    color: #a9abb0;
    font-style: italic;
  }

  .action-btns {
    display: flex;
    gap: 0.4rem;

    .el-button {
      padding: 0;
      width: 28px;
      height: 28px;
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 50%;
    }
  }
}

.pagination-container {
  background-color: #fafbfc;
  padding: 0.8rem;
  border-top: 1px solid #e6eaf0;
  display: flex;
  justify-content: center;
}

.text-center {
  text-align: center;
}

.py-4 {
  padding-top: 1rem;
  padding-bottom: 1rem;
}

.download-btn {
  display: flex;
  align-items: center;
  gap: 4px;
}

/* 对话框样式 */
.compact-dialog {
  :deep(.el-dialog__header) {
    padding: 16px 20px;
    border-bottom: 1px solid #ebeef5;
    margin-right: 0;
  }
  
  :deep(.el-dialog__title) {
    font-size: 18px;
    font-weight: 500;
    color: #303133;
  }
  
  :deep(.el-dialog__body) {
    padding: 20px;
  }
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .filter-bar {
    gap: 0.6rem;
    
    .input-short {
      width: 140px;
    }
  }
  
  .custom-table {
    font-size: 0.85rem;
    
    th, td {
      padding: 6px 8px;
    }
  }
}

@media (max-width: 992px) {
  .header {
    padding: 0.6rem 1rem;
    
    h2 {
      font-size: 1.2rem;
    }
  }
  
  .filter-bar {
    padding: 0.6rem 1rem;
  }
  
  .responsive-table-container {
    padding: 0.6rem;
  }
}
.file-preview-wrapper {
  margin-top: 8px;
  display: flex;
  align-items: center;
  position: relative;
}

.file-preview {
  position: relative;
  display: inline-block;
  cursor: pointer;
  width: 80px;
  height: 80px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
  background-color: #f5f7fa;
  text-align: center;
  line-height: 80px;
  color: #606266;
  font-size: 12px;
  transition: border-color 0.3s ease;
}

.file-preview:hover {
  border-color: #409eff;
}

.preview-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.file-name {
  display: block;
  padding: 0 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.file-hover-preview {
  position: absolute;
  top: 0;
  z-index: 20;
  display: none;
  background: white;
  padding: 6px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  min-width: 120px;
  max-width: 200px;
  max-height: 200px;
  white-space: normal;
}

.left-preview {
  right: 100%; // 左侧显示
  margin-right: 10px;
}

.zoom-img {
  width: 100%;
  height: auto;
  max-height: 180px;
  object-fit: contain;
}

.zoom-text {
  color: #303133;
  font-size: 14px;
  word-break: break-all;
}

.file-preview:hover .file-hover-preview {
  display: block;
}
.attachment-thumbnail {
  display: inline-block;
  width: 40px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  vertical-align: middle;
}

.thumbnail-img {
  max-width: 100%;
  max-height: 100%;
  border-radius: 4px;
  object-fit: cover;
  cursor: pointer;
  box-shadow: 0 0 3px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease;
}

.thumbnail-img:hover {
  transform: scale(1.1);
}

.attachment-thumbnail {
  display: inline-block;
  width: 40px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  vertical-align: middle;
}

.thumbnail-img {
  max-width: 100%;
  max-height: 100%;
  border-radius: 4px;
  object-fit: cover;
  cursor: pointer;
  box-shadow: 0 0 3px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease;
}

.thumbnail-img:hover {
  transform: scale(1.1);
}
.thumbnail-img {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  object-fit: cover;
  cursor: zoom-in;
  transition: transform 0.2s ease;
  margin-right: 4px;
  vertical-align: middle;
}

.thumbnail-img:hover {
  transform: scale(1.1);
}

.thumbnail-download {
  display: inline-block;
  width: 0;
  height: 0;
  overflow: hidden;
}
.thumbnail-img {
  width: 40px;
  height: 40px;
  object-fit: cover;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
  border: 1px solid #ddd;
}

.image-popover {
  padding: 0 !important;
  background-color: transparent !important;
  box-shadow: none !important;
  border: none !important;
}

.preview-img {
  width: 300px; // 放大图片
  height: auto;
  max-height: 400px;
  display: block;
  object-fit: contain;
  border: none;
  border-radius: 0;
  background: transparent;
}

.thumbnail-download {
  display: none; // 你也可以用按钮代替
}
</style>